package com.cool.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.cool.dto.request.QueryRequest;
import com.cool.dto.request.SortRequest;
import com.cool.mybatisplus.AgeConvertHandler;
import com.cool.pojo.CommonConstants;
import com.cool.pojo.Man;
import com.cool.service.ExportService;
import com.github.liaochong.myexcel.core.DefaultExcelBuilder;
import com.github.liaochong.myexcel.utils.FileExportUtil;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 导出服务
 * 
 * @author bian
 * @date 2021-05-27
 */
@RestController
@Slf4j
public class ExportController {
    @Autowired
    private ExportService exportService;

    @Autowired
    private AgeConvertHandler ageConvertHandler;

    /**
     * 导出Excel
     *
     * @param queryRequest 查询请求
     * @return 文件流
     * @throws IOException 导出异常
     */
    @GetMapping(value = "/export")
    public ResponseEntity<FileSystemResource> export(@RequestBody QueryRequest queryRequest) throws IOException {
        String uuid = IdUtil.fastUUID();
        // 更换成自己路径
        String fileName = "C:/Users/bian/Desktop/" + uuid + ".xlsx";
        List<String> order = queryRequest.getSortList().stream().map(SortRequest::getName).collect(Collectors.toList());
        List<Man> dataList = Man.getManList();
        Workbook workbook = DefaultExcelBuilder.of(Man.class).fieldDisplayOrder(order).binding(ageConvertHandler).build(dataList);
        File file = new File(fileName);
        FileExportUtil.export(workbook, file);
        return ResponseEntity.ok().headers(exportService.getHttpHeaders(file)).contentLength(file.length())
            .contentType(MediaType.parseMediaType(CommonConstants.EXCEL_MEDIA_TYPE)).body(new FileSystemResource(file));
    }

}
